const { get } = require('../../../utils/request');
const { COLLECT_API } = require('../../../utils/api');

Page({
  data: {
    favoritesList: [], // 收藏列表数据
    loading: false, // 加载状态
    userId: 1 // 用户ID，暂时固定为1
  },

  onLoad() {
    this.getFavoritesList();
  },

  onShow() {
    // 页面显示时刷新数据，确保从其他页面返回时数据是最新的
    console.log('favorites页面显示，刷新数据');
    this.getFavoritesList();
  },

  // 获取收藏列表数据
  async getFavoritesList() {
    try {
      this.setData({ loading: true });
      
      const url = `${COLLECT_API.USER_COLLECTIONS}/${this.data.userId}`;
      const result = await get(url);
      
      if (result && result.data) {
        this.setData({
          favoritesList: result.data,
          loading: false
        });
        console.log("ee", this.data.favoritesList)
      } else {
        this.setData({ loading: false });
        wx.showToast({
          title: '暂无收藏数据',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('获取收藏列表失败:', error);
      this.setData({ loading: false });
      
      // 如果API请求失败，显示默认数据
      this.setDefaultData();
      
      wx.showToast({
        title: '获取数据失败，显示默认内容',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 设置默认数据（当API请求失败时使用）
  setDefaultData() {
    const defaultData = [
      {
        id: 'airfryer',
        name: '空气炸锅',
        image: '/images/airfryer.png',
        type: 'airfryer'
      },
      {
        id: 'noodle',
        name: '面条',
        image: '/images/noodle.png',
        type: 'noodle'
      },
      {
        id: 'cake',
        name: '蛋糕',
        image: '/images/cake6.png',
        type: 'cake'
      },
      {
        id: 'mooncake',
        name: '月饼',
        image: '/images/mooncake.png',
        type: 'mooncake'
      }
    ];
    
    this.setData({
      favoritesList: defaultData
    });
  },

  // 图片加载错误处理
  imageError(e) {
    console.error('图片加载失败:', e.detail.errMsg);
    // 可以设置默认图片
    const index = e.currentTarget.dataset.index;
    const defaultImage = '/images/default-food.png'; // 默认图片路径
    
    if (index !== undefined && this.data.favoritesList[index]) {
      const favoritesList = [...this.data.favoritesList];
      favoritesList[index].image = defaultImage;
      this.setData({ favoritesList });
    }
  },

  // 跳转到详情页
  navigateToDetail(e) {
    const index = e.currentTarget.dataset.index;
    const currentItem = this.data.favoritesList[index];

    console.log("rrr",currentItem)
    
    if (currentItem && currentItem.collectionId) {
      const url = `/collect/pages/FolderCookbook/FolderCookbook?id=${currentItem.collectionId}&name=${currentItem.collectionName}`;
      
      wx.navigateTo({
        url: url,
        fail: (err) => {
          console.error('页面跳转失败:', err);
          wx.showToast({
            title: '跳转失败，请稍后重试',
            icon: 'none',
            duration: 2000
          });
        }
      });
    } else {
      wx.showToast({
        title: '数据错误，请稍后重试',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.getFavoritesList().then(() => {
      wx.stopPullDownRefresh();
    });
  }
});
    